<template>
  <div class="project-enrollment">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h2>运动项目报名</h2>
        <p>选择您感兴趣的项目，填写健康声明后即可完成报名</p>
      </div>
      <div class="header-actions">
        <el-button type="default" icon="Refresh" @click="fetchProjects">刷新</el-button>
        <el-button type="primary" icon="List" @click="viewMyEnrollments">我的报名</el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-section">
      <el-col :span="6">
        <el-card class="stat-card total">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Grid /></el-icon>
            </div>
            <div class="stat-info">
              <h3>全部项目</h3>
              <p class="stat-number">{{ totalProjects }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card available">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stat-info">
              <h3>可报名</h3>
              <p class="stat-number">{{ availableProjects }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card enrolled">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><UserFilled /></el-icon>
            </div>
            <div class="stat-info">
              <h3>已报名</h3>
              <p class="stat-number">{{ myEnrollmentsCount }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card hot">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-info">
              <h3>热门项目</h3>
              <p class="stat-number">{{ hotProjectsCount }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 筛选区域 -->
    <el-card class="filter-card" shadow="never">
      <div class="filter-header">
        <h3>筛选条件</h3>
        <el-button type="text" @click="toggleFilter">
          {{ showFilter ? '收起' : '展开' }}
          <el-icon class="ml-1">
            <component :is="showFilter ? 'ArrowUp' : 'ArrowDown'" />
          </el-icon>
        </el-button>
      </div>
      <el-collapse-transition>
        <div v-show="showFilter">
          <el-form :inline="true" :model="searchForm" class="filter-form">
            <el-form-item label="项目名称">
              <el-input
                v-model="searchForm.name"
                placeholder="请输入项目名称"
                clearable
                @keyup.enter="handleSearch"
              />
            </el-form-item>
            <el-form-item label="项目类型">
              <el-select v-model="searchForm.type" placeholder="请选择项目类型" clearable>
                <el-option
                  v-for="type in projectTypes"
                  :key="type"
                  :label="type"
                  :value="type"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="性别限制">
              <el-select v-model="searchForm.genderLimit" placeholder="请选择性别限制" clearable>
                <el-option label="无限制" value="无" />
                <el-option label="仅限男生" value="男" />
                <el-option label="仅限女生" value="女" />
              </el-select>
            </el-form-item>
            <el-form-item label="项目状态">
              <el-select v-model="searchForm.status" placeholder="请选择项目状态" clearable>
                <el-option label="报名中" value="报名中" />
                <el-option label="未开始" value="未开始" />
                <el-option label="进行中" value="进行中" />
                <el-option label="已结束" value="已结束" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
              <el-button icon="Refresh" @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-collapse-transition>
    </el-card>

    <!-- 项目列表 -->
    <div class="project-container">
      <!-- 视图切换 -->
      <div class="view-controls">
        <div class="view-switch">
          <el-button-group>
            <el-button
              :type="viewMode === 'grid' ? 'primary' : 'default'"
              icon="Grid"
              @click="viewMode = 'grid'"
            >
              网格视图
            </el-button>
            <el-button
              :type="viewMode === 'list' ? 'primary' : 'default'"
              icon="List"
              @click="viewMode = 'list'"
            >
              列表视图
            </el-button>
          </el-button-group>
        </div>
        <div class="sort-controls">
          <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort">
            <el-option label="默认排序" value="" />
            <el-option label="报名人数" value="registrationCount" />
            <el-option label="创建时间" value="createdAt" />
            <el-option label="比赛时间" value="competitionTime" />
          </el-select>
        </div>
      </div>

      <!-- 项目内容 -->
      <el-loading :loading="loading" element-loading-text="加载中...">
        <!-- 网格视图 -->
        <div v-if="viewMode === 'grid'" class="project-grid">
          <el-empty v-if="projectList.length === 0" description="暂无项目数据">
            <el-button type="primary" @click="resetSearch">重置筛选</el-button>
          </el-empty>
          <el-row v-else :gutter="20">
            <el-col
              v-for="project in projectList"
              :key="project.id"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
            >
              <el-card class="project-card" shadow="hover" @click="handleViewDetails(project)">
                <div class="project-header">
                  <div class="project-type-tag">
                    <el-tag :type="getProjectTypeTagType(project.type)" size="small">
                      {{ project.type }}
                    </el-tag>
                  </div>
                  <div class="project-status">
                    <el-tag :type="getProjectStatusTagType(project.status)" size="small">
                      {{ project.status }}
                    </el-tag>
                  </div>
                </div>
                <div class="project-body">
                  <h4 class="project-name">{{ project.name }}</h4>
                  <div class="project-info">
                    <div class="info-item">
                      <el-icon><Clock /></el-icon>
                      <span>{{ project.competitionTime || '待定' }}</span>
                    </div>
                    <div class="info-item">
                      <el-icon><Location /></el-icon>
                      <span>{{ project.location || '待定' }}</span>
                    </div>
                    <div class="info-item">
                      <el-icon><User /></el-icon>
                      <span>{{ getGenderLimitText(project.genderLimit) }}</span>
                    </div>
                    <div class="info-item" v-if="project.maxPlayers > 0">
                      <el-icon><Limit /></el-icon>
                      <span>限{{ project.maxPlayers }}人</span>
                    </div>
                  </div>
                  <div class="project-progress">
                    <div class="progress-info">
                      <span>报名进度</span>
                      <span>{{ project.registrationCount || 0 }}{{ project.maxPlayers > 0 ? '/' + project.maxPlayers : '' }}人</span>
                    </div>
                    <el-progress
                      :percentage="project.maxPlayers > 0 ? (project.registrationCount / project.maxPlayers * 100) : 0"
                      :color="getProgressColor(project)"
                      :show-text="false"
                    />
                  </div>
                </div>
                <div class="project-footer">
                  <el-button
                    v-if="canEnroll(project)"
                    type="primary"
                    size="small"
                    @click.stop="handleEnroll(project)"
                  >
                    立即报名
                  </el-button>
                  <el-button
                    v-else-if="isEnrolled(project)"
                    type="danger"
                    size="small"
                    @click.stop="handleCancel(project)"
                  >
                    取消报名
                  </el-button>
                  <el-button
                    v-else
                    size="small"
                    disabled
                    @click.stop
                  >
                    {{ getEnrollButtonText(project) }}
                  </el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 列表视图 -->
        <div v-else class="project-list">
          <el-empty v-if="projectList.length === 0" description="暂无项目数据">
            <el-button type="primary" @click="resetSearch">重置筛选</el-button>
          </el-empty>
          <el-table v-else :data="projectList" stripe>
            <el-table-column prop="name" label="项目名称" min-width="150">
              <template #default="{ row }">
                <div class="project-name-cell">
                  <h4>{{ row.name }}</h4>
                  <el-tag :type="getProjectTypeTagType(row.type)" size="small">
                    {{ row.type }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="competitionTime" label="比赛时间" width="160">
              <template #default="{ row }">
                <div class="time-cell">
                  <el-icon><Clock /></el-icon>
                  <span>{{ row.competitionTime || '待定' }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="location" label="比赛地点" width="120">
              <template #default="{ row }">
                <div class="location-cell">
                  <el-icon><Location /></el-icon>
                  <span>{{ row.location || '待定' }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="genderLimit" label="性别限制" width="100">
              <template #default="{ row }">
                <span>{{ getGenderLimitText(row.genderLimit) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="maxPlayers" label="人数限制" width="100">
              <template #default="{ row }">
                {{ row.maxPlayers === 0 ? '无限制' : row.maxPlayers + '人' }}
              </template>
            </el-table-column>
            <el-table-column prop="registrationCount" label="报名情况" width="150">
              <template #default="{ row }">
                <div class="registration-cell">
                  <span>{{ row.registrationCount || 0 }}人</span>
                  <el-progress
                    v-if="row.maxPlayers > 0"
                    :percentage="(row.registrationCount / row.maxPlayers * 100)"
                    :color="getProgressColor(row)"
                    :show-text="false"
                    :stroke-width="4"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getProjectStatusTagType(row.status)">
                  {{ row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button
                  v-if="canEnroll(row)"
                  type="primary"
                  size="small"
                  @click="handleEnroll(row)"
                >
                  报名
                </el-button>
                <el-button
                  v-else-if="isEnrolled(row)"
                  type="danger"
                  size="small"
                  @click="handleCancel(row)"
                >
                  取消报名
                </el-button>
                <el-button
                  v-else
                  size="small"
                  disabled
                >
                  {{ getEnrollButtonText(row) }}
                </el-button>
                <el-button
                  type="info"
                  size="small"
                  @click="handleViewDetails(row)"
                >
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <div v-if="projectList.length > 0" class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[12, 24, 36, 48]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-loading>
    </div>

    <!-- 项目详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="selectedProject?.name"
      width="700px"
      destroy-on-close
    >
      <div v-if="selectedProject" class="project-detail">
        <div class="detail-header">
          <div class="detail-title">
            <h3>{{ selectedProject.name }}</h3>
            <div class="detail-tags">
              <el-tag :type="getProjectTypeTagType(selectedProject.type)">
                {{ selectedProject.type }}
              </el-tag>
              <el-tag :type="getProjectStatusTagType(selectedProject.status)">
                {{ selectedProject.status }}
              </el-tag>
              <el-tag v-if="selectedProject.maxPlayers > 0" type="info">
                限{{ selectedProject.maxPlayers }}人
              </el-tag>
            </div>
          </div>
          <div class="enrollment-status">
            <div v-if="isEnrolled(selectedProject)" class="enrolled-info">
              <el-icon color="#67C23A"><CircleCheckFilled /></el-icon>
              <span>已报名</span>
            </div>
            <div v-else-if="canEnroll(selectedProject)" class="can-enroll-info">
              <el-icon color="#409EFF"><Plus /></el-icon>
              <span>可以报名</span>
            </div>
            <div v-else class="cannot-enroll-info">
              <el-icon color="#F56C6C"><CircleCloseFilled /></el-icon>
              <span>{{ getEnrollButtonText(selectedProject) }}</span>
            </div>
          </div>
        </div>

        <el-descriptions :column="2" border class="detail-descriptions">
          <el-descriptions-item label="比赛时间">
            {{ selectedProject.competitionTime || '待定' }}
          </el-descriptions-item>
          <el-descriptions-item label="比赛地点">
            {{ selectedProject.location || '待定' }}
          </el-descriptions-item>
          <el-descriptions-item label="性别限制">
            {{ getGenderLimitText(selectedProject.genderLimit) }}
          </el-descriptions-item>
          <el-descriptions-item label="人数限制">
            {{ selectedProject.maxPlayers === 0 ? '无限制' : selectedProject.maxPlayers + '人' }}
          </el-descriptions-item>
          <el-descriptions-item label="轮次数量">
            {{ selectedProject.rounds || 1 }}轮
          </el-descriptions-item>
          <el-descriptions-item label="报名人数">
            {{ selectedProject.registrationCount || 0 }}人
            <span v-if="selectedProject.maxPlayers > 0">
              / {{ selectedProject.maxPlayers }}人
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="报名时间" :span="2">
            {{ selectedProject.registrationStartTime || '开始时间待定' }} 至
            {{ selectedProject.registrationEndTime || '结束时间待定' }}
          </el-descriptions-item>
          <el-descriptions-item label="项目说明" :span="2">
            <div v-if="selectedProject.description" class="project-description">
              {{ selectedProject.description }}
            </div>
            <span v-else class="text-placeholder">暂无说明</span>
          </el-descriptions-item>
          <el-descriptions-item label="比赛规则" :span="2">
            <div v-if="selectedProject.ruleDescription" class="project-rules">
              {{ selectedProject.ruleDescription }}
            </div>
            <span v-else class="text-placeholder">暂无规则说明</span>
          </el-descriptions-item>
        </el-descriptions>

        <div class="detail-actions">
          <el-button
            v-if="canEnroll(selectedProject)"
            type="primary"
            size="large"
            @click="handleEnroll(selectedProject)"
          >
            立即报名
          </el-button>
          <el-button
            v-else-if="isEnrolled(selectedProject)"
            type="danger"
            size="large"
            @click="handleCancel(selectedProject)"
          >
            取消报名
          </el-button>
          <el-button
            v-else
            size="large"
            disabled
          >
            {{ getEnrollButtonText(selectedProject) }}
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 报名对话框 -->
    <el-dialog
      v-model="enrollDialogVisible"
      title="项目报名确认"
      width="600px"
      destroy-on-close
      @close="resetEnrollForm"
    >
      <div v-if="selectedProject" class="enrollment-confirm">
        <div class="confirm-project-info">
          <h4>{{ selectedProject.name }}</h4>
          <div class="project-meta">
            <el-tag :type="getProjectTypeTagType(selectedProject.type)">
              {{ selectedProject.type }}
            </el-tag>
            <span class="separator">|</span>
            <span>{{ getGenderLimitText(selectedProject.genderLimit) }}</span>
            <span class="separator">|</span>
            <span>{{ selectedProject.competitionTime || '时间待定' }}</span>
            <span class="separator">|</span>
            <span>{{ selectedProject.location || '地点待定' }}</span>
          </div>
        </div>

        <el-alert
          title="报名须知"
          type="warning"
          :closable="false"
          show-icon
          class="enrollment-notice"
        >
          <template #default>
            <ul class="notice-list">
              <li>请确保您身体健康，适合参加此项运动</li>
              <li>请按时参加比赛，迟到将取消参赛资格</li>
              <li>报名后请留意比赛通知，如有变动将及时通知</li>
              <li>遵守比赛规则和体育道德精神</li>
            </ul>
          </template>
        </el-alert>

        <el-form
          ref="enrollFormRef"
          :model="enrollForm"
          :rules="enrollFormRules"
          label-width="120px"
          class="enrollment-form"
        >
          <el-form-item label="健康声明" prop="healthStatement">
            <el-input
              v-model="enrollForm.healthStatement"
              type="textarea"
              :rows="4"
              placeholder="请输入健康声明，确认您身体健康状况适合参加此项运动..."
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="备注信息">
            <el-input
              v-model="enrollForm.remarks"
              type="textarea"
              :rows="3"
              placeholder="如有特殊需求或情况说明，请在此填写（选填）"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="enrollDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmEnroll" :loading="enrollLoading">
            确认报名
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 我的报名对话框 -->
    <el-dialog
      v-model="myEnrollmentsVisible"
      title="我的报名项目"
      width="800px"
      destroy-on-close
    >
      <div v-loading="myEnrollmentsLoading" class="my-enrollments-content">
        <el-empty v-if="myEnrollments.length === 0" description="您还没有报名任何项目">
          <el-button type="primary" @click="myEnrollmentsVisible = false; fetchProjects()">
            去报名
          </el-button>
        </el-empty>
        <div v-else class="enrollments-list">
          <div
            v-for="enrollment in myEnrollments"
            :key="enrollment.id"
            class="enrollment-item"
          >
            <div class="enrollment-header">
              <h4>{{ enrollment.projectName }}</h4>
              <el-tag :type="getEnrollmentStatusType(enrollment.status)">
                {{ getEnrollmentStatusText(enrollment.status) }}
              </el-tag>
            </div>
            <div class="enrollment-info">
              <div class="info-row">
                <span class="label">报名时间：</span>
                <span class="value">{{ enrollment.enrollTime }}</span>
              </div>
              <div class="info-row">
                <span class="label">比赛时间：</span>
                <span class="value">{{ enrollment.competitionTime || '待定' }}</span>
              </div>
              <div class="info-row" v-if="enrollment.score !== null">
                <span class="label">成绩：</span>
                <span class="value score">{{ enrollment.score }}</span>
              </div>
              <div class="info-row" v-if="enrollment.rank">
                <span class="label">名次：</span>
                <span class="value rank">{{ enrollment.rank }}</span>
              </div>
            </div>
            <div class="enrollment-actions">
              <el-button
                v-if="enrollment.status === 'PENDING'"
                type="danger"
                size="small"
                @click="handleCancelByEnrollment(enrollment)"
              >
                取消报名
              </el-button>
              <el-button
                type="info"
                size="small"
                @click="viewEnrollmentDetails()"
              >
                查看详情
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Grid, Check, UserFilled, Star, Clock, Location, User, Limit,
  Plus, CircleCheckFilled, CircleCloseFilled
} from '@element-plus/icons-vue'
import {
  getProjectPage,
  enrollProject,
  cancelEnrollment,
  getEnrollmentsByUserId
} from '@/api/enrollment'
import { getProjectTypes } from '@/api/project'

// 获取用户信息
const authStore = useAuthStore()
const currentUser = computed(() => authStore.userInfo)

// 响应式数据
const loading = ref(false)
const enrollLoading = ref(false)
const myEnrollmentsLoading = ref(false)
const projectList = ref([])
const selectedProject = ref(null)
const detailDialogVisible = ref(false)
const enrollDialogVisible = ref(false)
const myEnrollmentsVisible = ref(false)
const showFilter = ref(true)
const viewMode = ref('grid')
const sortBy = ref('')

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 12,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  genderLimit: '',
  status: ''
})

// 报名表单
const enrollFormRef = ref()
const enrollForm = reactive({
  projectId: null,
  projectName: '',
  healthStatement: '',
  remarks: ''
})

// 报名表单验证规则
const enrollFormRules = {
  healthStatement: [
    { required: true, message: '请输入健康声明', trigger: 'blur' },
    { min: 10, max: 500, message: '健康声明长度应在10-500字符之间', trigger: 'blur' }
  ]
}

// 项目类型列表
const projectTypes = ref(['径赛', '田赛', '球类', '其他'])

// 用户报名记录
const myEnrollments = ref([])

// 统计数据
const totalProjects = ref(0)
const availableProjects = ref(0)
const myEnrollmentsCount = ref(0)
const hotProjectsCount = ref(0)

// 计算属性和方法
const canEnroll = (project) => {
  if (project.status !== '报名中') return false
  if (project.maxPlayers > 0 && (project.registrationCount || 0) >= project.maxPlayers) return false
  if (isEnrolled(project)) return false
  if (project.genderLimit !== '无' && project.genderLimit !== currentUser.value.gender) return false
  return true
}

const isEnrolled = (project) => {
  return myEnrollments.value.some(enrollment =>
    enrollment.projectId === project.id &&
    enrollment.status !== 'CANCELLED'
  )
}

const getEnrollButtonText = (project) => {
  if (project.status !== '报名中') return '未开放报名'
  if (project.maxPlayers > 0 && (project.registrationCount || 0) >= project.maxPlayers) return '人数已满'
  if (isEnrolled(project)) return '已报名'
  if (project.genderLimit !== '无' && project.genderLimit !== currentUser.value.gender) return '性别不符'
  return '不可报名'
}

const getProjectTypeTagType = (type) => {
  const typeMap = {
    '径赛': 'primary',
    '田赛': 'success',
    '球类': 'warning',
    '其他': 'info'
  }
  return typeMap[type] || 'info'
}

const getProjectStatusTagType = (status) => {
  const statusMap = {
    '未开始': 'info',
    '报名中': 'success',
    '进行中': 'warning',
    '已结束': 'danger',
    '已取消': 'info'
  }
  return statusMap[status] || 'info'
}

const getEnrollmentStatusType = (status) => {
  const statusMap = {
    'PENDING': 'warning',
    'APPROVED': 'success',
    'COMPLETED': 'info',
    'CANCELLED': 'danger'
  }
  return statusMap[status] || 'info'
}

const getEnrollmentStatusText = (status) => {
  const statusMap = {
    'PENDING': '待审核',
    'APPROVED': '已通过',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return statusMap[status] || status
}

const getGenderLimitText = (genderLimit) => {
  const genderMap = {
    'MALE': '仅限男生',
    'FEMALE': '仅限女生',
    'ALL': '无限制',
    '男': '仅限男生',
    '女': '仅限女生',
    '无': '无限制'
  }
  return genderMap[genderLimit] || '无限制'
}

const getProgressColor = (project) => {
  if (project.maxPlayers === 0) return '#409EFF'

  const percentage = (project.registrationCount || 0) / project.maxPlayers * 100
  if (percentage >= 90) return '#F56C6C'
  if (percentage >= 70) return '#E6A23C'
  return '#67C23A'
}

// API调用方法
const fetchProjects = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize,
      sortBy: sortBy.value
    }

    const response = await getProjectPage(pagination.currentPage, pagination.pageSize, params)

    if (response.code === 200) {
      projectList.value = response.data.records || []
      pagination.total = response.data.total || 0

      // 更新统计数据
      totalProjects.value = response.data.total || 0
      availableProjects.value = projectList.value.filter(p => canEnroll(p)).length
      hotProjectsCount.value = projectList.value.filter(p => (p.registrationCount || 0) >= (p.maxPlayers * 0.7)).length
    } else {
      ElMessage.error(response.message || '获取项目列表失败')
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
    ElMessage.error('获取项目列表失败')
    // 使用模拟数据
    loadMockProjects()
  } finally {
    loading.value = false
  }
}

const fetchMyEnrollments = async () => {
  myEnrollmentsLoading.value = true
  try {
    const response = await getEnrollmentsByUserId(currentUser.value.userId)
    if (response.code === 200) {
      myEnrollments.value = response.data || []
      myEnrollmentsCount.value = myEnrollments.value.filter(e => e.status !== 'CANCELLED').length
    }
  } catch (error) {
    console.error('获取我的报名记录失败:', error)
    // 使用模拟数据
    loadMockEnrollments()
  } finally {
    myEnrollmentsLoading.value = false
  }
}

const fetchProjectTypes = async () => {
  try {
    const response = await getProjectTypes()
    if (response.code === 200) {
      projectTypes.value = response.data || ['径赛', '田赛', '球类', '其他']
    }
  } catch (error) {
    console.error('获取项目类型失败:', error)
  }
}

// 加载模拟数据
const loadMockProjects = () => {
  projectList.value = [
    {
      id: 1,
      name: '100米短跑',
      type: '径赛',
      genderLimit: '男',
      maxPlayers: 50,
      registrationCount: 32,
      status: '报名中',
      competitionTime: '2025-10-15 14:00',
      location: '操场第一跑道',
      rounds: 3,
      description: '标准100米短跑比赛，分预赛、复赛和决赛三轮',
      ruleDescription: '采用国际田联最新规则，起跑采用蹲踞式，使用起跑器',
      registrationStartTime: '2025-10-10 08:00',
      registrationEndTime: '2025-10-14 18:00',
      createdAt: '2025-10-08 10:00:00'
    },
    {
      id: 2,
      name: '跳远',
      type: '田赛',
      genderLimit: '无',
      maxPlayers: 40,
      registrationCount: 28,
      status: '报名中',
      competitionTime: '2025-10-16 10:00',
      location: '沙坑区',
      rounds: 2,
      description: '立定跳远和助跑跳远，每人三次机会',
      ruleDescription: '取最好成绩作为最终成绩，测量从起跳线到落地点最近点的距离',
      registrationStartTime: '2025-10-10 08:00',
      registrationEndTime: '2025-10-14 18:00',
      createdAt: '2025-10-08 11:00:00'
    },
    {
      id: 3,
      name: '铅球',
      type: '田赛',
      genderLimit: '男',
      maxPlayers: 30,
      registrationCount: 30,
      status: '报名中',
      competitionTime: '2025-10-16 14:00',
      location: '投掷区',
      rounds: 2,
      description: '男子铅球比赛，重量5公斤',
      ruleDescription: '采用旋转式或滑步式投掷技术，每人三次机会',
      registrationStartTime: '2025-10-10 08:00',
      registrationEndTime: '2025-10-14 18:00',
      createdAt: '2025-10-08 12:00:00'
    },
    {
      id: 4,
      name: '4x100米接力',
      type: '径赛',
      genderLimit: '男',
      maxPlayers: 16,
      registrationCount: 12,
      status: '报名中',
      competitionTime: '2025-10-17 10:00',
      location: '操场第一跑道',
      rounds: 2,
      description: '4人100米接力比赛，需要提前组队',
      ruleDescription: '每队4人，采用标准接力棒传递方式，交接棒必须在指定区域内完成',
      registrationStartTime: '2025-10-10 08:00',
      registrationEndTime: '2025-10-14 18:00',
      createdAt: '2025-10-08 13:00:00'
    },
    {
      id: 5,
      name: '跳高',
      type: '田赛',
      genderLimit: '女',
      maxPlayers: 25,
      registrationCount: 18,
      status: '报名中',
      competitionTime: '2025-10-16 15:00',
      location: '跳高区',
      rounds: 3,
      description: '女子跳高比赛，采用横杆式',
      ruleDescription: '每人每高度三次机会，失败三次即被淘汰，高度逐渐递增',
      registrationStartTime: '2025-10-10 08:00',
      registrationEndTime: '2025-10-14 18:00',
      createdAt: '2025-10-08 14:00:00'
    }
  ]

  pagination.total = projectList.value.length
  totalProjects.value = projectList.value.length
  availableProjects.value = projectList.value.filter(p => canEnroll(p)).length
  hotProjectsCount.value = projectList.value.filter(p => (p.registrationCount || 0) >= (p.maxPlayers * 0.7)).length
}

const loadMockEnrollments = () => {
  myEnrollments.value = [
    {
      id: 1,
      projectId: 1,
      projectName: '100米短跑',
      status: 'APPROVED',
      enrollTime: '2025-10-12 10:30:00',
      competitionTime: '2025-10-15 14:00',
      score: null,
      rank: null
    }
  ]
  myEnrollmentsCount.value = myEnrollments.value.filter(e => e.status !== 'CANCELLED').length
}

// 事件处理方法
const handleSearch = () => {
  pagination.currentPage = 1
  fetchProjects()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    name: '',
    type: '',
    genderLimit: '',
    status: ''
  })
  handleSearch()
}

const handleSort = () => {
  fetchProjects()
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchProjects()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchProjects()
}

const toggleFilter = () => {
  showFilter.value = !showFilter.value
}

const handleViewDetails = (project) => {
  selectedProject.value = project
  detailDialogVisible.value = true
}

const handleEnroll = (project) => {
  enrollForm.projectId = project.id
  enrollForm.projectName = project.name
  enrollForm.healthStatement = ''
  enrollForm.remarks = ''
  enrollDialogVisible.value = true
}

const handleConfirmEnroll = async () => {
  try {
    await enrollFormRef.value.validate()

    enrollLoading.value = true

    const response = await enrollProject({
      projectId: enrollForm.projectId,
      healthStatement: enrollForm.healthStatement,
      remarks: enrollForm.remarks
    })

    if (response.code === 200) {
      ElMessage.success('报名成功，请等待审核')
      enrollDialogVisible.value = false
      fetchProjects()
      fetchMyEnrollments()
    } else {
      ElMessage.error(response.message || '报名失败')
    }
  } catch (error) {
    if (error.name !== 'ElFormValidateError') {
      console.error('报名失败:', error)
      ElMessage.error('报名失败')
    }
  } finally {
    enrollLoading.value = false
  }
}

const handleCancel = async (project) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消报名吗？取消后需要重新报名。',
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const enrollment = myEnrollments.value.find(e =>
      e.projectId === project.id && e.status !== 'CANCELLED'
    )

    if (enrollment) {
      const response = await cancelEnrollment(enrollment.id)
      if (response.code === 200) {
        ElMessage.success('取消报名成功')
        fetchProjects()
        fetchMyEnrollments()
      } else {
        ElMessage.error(response.message || '取消报名失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消报名失败:', error)
      ElMessage.error('取消报名失败')
    }
  }
}

const handleCancelByEnrollment = async (enrollment) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消报名吗？取消后需要重新报名。',
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await cancelEnrollment(enrollment.id)
    if (response.code === 200) {
      ElMessage.success('取消报名成功')
      fetchMyEnrollments()
      fetchProjects()
    } else {
      ElMessage.error(response.message || '取消报名失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消报名失败:', error)
      ElMessage.error('取消报名失败')
    }
  }
}

const viewMyEnrollments = () => {
  myEnrollmentsVisible.value = true
  fetchMyEnrollments()
}

const viewEnrollmentDetails = () => {
  ElMessage.info('报名详情功能开发中')
}

const resetEnrollForm = () => {
  enrollFormRef.value?.resetFields()
  Object.assign(enrollForm, {
    projectId: null,
    projectName: '',
    healthStatement: '',
    remarks: ''
  })
}

// 生命周期钩子
onMounted(async () => {
  await Promise.all([
    fetchProjects(),
    fetchMyEnrollments(),
    fetchProjectTypes()
  ])
})
</script>

<style scoped>
/* 整体布局 */
.project-enrollment {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.header-content h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.header-content p {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 统计卡片 */
.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 12px;
  overflow: hidden;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 28px;
  color: white;
}

.stat-card.total .stat-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-card.available .stat-icon {
  background: linear-gradient(135deg, #56CCF2 0%, #2F80ED 100%);
}

.stat-card.enrolled .stat-icon {
  background: linear-gradient(135deg, #4776E6 0%, #8E54E9 100%);
}

.stat-card.hot .stat-icon {
  background: linear-gradient(135deg, #F093FB 0%, #F5576C 100%);
}

.stat-info h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #606266;
  font-weight: normal;
}

.stat-number {
  margin: 0;
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

/* 筛选区域 */
.filter-card {
  margin-bottom: 24px;
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.filter-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
  font-weight: 600;
}

.filter-form {
  padding: 20px;
}

/* 项目容器 */
.project-container {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

/* 视图控制 */
.view-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.sort-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 网格视图 */
.project-grid {
  margin-bottom: 20px;
}

.project-card {
  height: 100%;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 12px;
  overflow: hidden;
}

.project-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.project-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.project-body {
  margin-bottom: 16px;
}

.project-name {
  margin: 0 0 12px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
}

.project-info {
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
}

.info-item .el-icon {
  margin-right: 8px;
  color: #909399;
}

.project-progress {
  margin-top: 16px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.project-footer {
  text-align: center;
}

/* 列表视图 */
.project-list {
  margin-bottom: 20px;
}

.project-name-cell h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  color: #303133;
}

.time-cell,
.location-cell {
  display: flex;
  align-items: center;
  color: #606266;
}

.time-cell .el-icon,
.location-cell .el-icon {
  margin-right: 6px;
  color: #909399;
}

.registration-cell {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

/* 项目详情对话框 */
.project-detail {
  padding: 16px 0;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.detail-title h3 {
  margin: 0 0 12px 0;
  font-size: 20px;
  color: #303133;
}

.detail-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.enrollment-status {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
}

.enrolled-info {
  color: #67C23A;
}

.can-enroll-info {
  color: #409EFF;
}

.cannot-enroll-info {
  color: #F56C6C;
}

.detail-descriptions {
  margin-bottom: 24px;
}

.project-description,
.project-rules {
  color: #606266;
  line-height: 1.6;
}

.text-placeholder {
  color: #c0c4cc;
  font-style: italic;
}

.detail-actions {
  text-align: center;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

/* 报名对话框 */
.enrollment-confirm {
  padding: 16px 0;
}

.confirm-project-info {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f8fafc;
  border-radius: 8px;
}

.confirm-project-info h4 {
  margin: 0 0 12px 0;
  font-size: 18px;
  color: #303133;
}

.project-meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.separator {
  color: #dcdfe6;
}

.enrollment-notice {
  margin-bottom: 20px;
}

.notice-list {
  margin: 0;
  padding-left: 20px;
}

.notice-list li {
  margin-bottom: 4px;
  color: #e6a23c;
}

.enrollment-form {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

/* 我的报名对话框 */
.my-enrollments-content {
  min-height: 200px;
}

.enrollments-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.enrollment-item {
  padding: 16px;
  background-color: #fafbfc;
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.enrollment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.enrollment-header h4 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.enrollment-info {
  margin-bottom: 12px;
}

.info-row {
  display: flex;
  margin-bottom: 6px;
  font-size: 14px;
}

.info-row .label {
  color: #909399;
  min-width: 80px;
}

.info-row .value {
  color: #303133;
}

.info-row .value.score {
  color: #67C23A;
  font-weight: bold;
}

.info-row .value.rank {
  color: #e6a23c;
  font-weight: bold;
}

.enrollment-actions {
  display: flex;
  gap: 8px;
}


/* 工具类 */
.ml-1 {
  margin-left: 0.25rem;
}
</style>